package 基础;
//udp客户端
import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp ;
    private int serverPort;

    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        this.serverPort = serverPort;
        this.serverIp = serverIp; 
        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("客户端启动!");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.print("请输入：");
//            1.从控制台中获取发送的请求数据
            if(!scanner.hasNext()){
                break;
            }
            //将数据转为字符串格式
            String request = scanner.next();
//            2.将请求数据构造成数据报，并发送
            //其中数据报中包括，内容，长度，服务端的ip，服务端的端口号
            DatagramPacket requestPack = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            //发送请求
            socket.send(requestPack);
//            3.服务器的响应
            //创建一个空的字节数组来接受响应
            DatagramPacket respondPack = new DatagramPacket(new byte[1024],1024);
            //从缓存区接受数据报保存在respondPack中
            socket.receive(respondPack);
//            4.将数据报中的内容显示到控制台
            String respond = new String(respondPack.getData(),0,respondPack.getLength());
            System.out.println("服务端的回应："+respond);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
